package org.aaron.demos.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {

	public static final int RESULT_SUCCESS = 0;
	public static final int RESULT_FAIL = -1;
	public static final int RESULT_FILE_IS_EXIST = 1;
	private String sdpath;

	public String getSdpath() {
		return sdpath;
	}

	public FileUtils() {
		sdpath = Environment.getExternalStorageDirectory() + File.separator;
	}

	/**
	 * 在sd卡上创建目录 返回0创建成功 返回-1创建失败
	 * 
	 * @param pathname
	 * @return
	 */
	public int create2SdDir(String pathname) {
		File file = new File(sdpath + pathname);
		if (file.mkdir()) {
			return FileUtils.RESULT_SUCCESS;
		}
		return FileUtils.RESULT_FAIL;
	}

	/**
	 * 在sd卡上创建文件 返回0创建成功 返回-1创建失败
	 * 
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public int create2SdFile(String filename) throws IOException {
		File file = new File(sdpath + filename);
		if (file.createNewFile()) {
			return FileUtils.RESULT_SUCCESS;
		}
		return FileUtils.RESULT_FAIL;
	}

	/**
	 * 在sd卡上文件是否存在 返回1已存在 返回-1文件不存在
	 * 
	 * @param filename
	 * @return
	 */
	public int IsExist2SdFile(String filename) {
		File file = new File(sdpath + filename);
		if (file.exists()) {
			return FileUtils.RESULT_FILE_IS_EXIST;
		}
		return FileUtils.RESULT_FAIL;
	}

	/**
	 * 在sd卡上写入文件流  返回0 写入成功  返回-1写入失败 
	 * @param path
	 * @param filename
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public int write2SdFromInput(String path, String filename, InputStream inputStream) throws IOException {
		OutputStream outputStream=null;
		String fullpath=getSdpath()+path+filename;
		if(FileUtils.RESULT_SUCCESS==create2SdDir(path)){
			if(FileUtils.RESULT_SUCCESS==create2SdFile(path+filename)){
				outputStream=new FileOutputStream(fullpath);
				byte[] buffer=new byte[1024*4];
				while((inputStream.read(buffer)!=-1)){
					outputStream.write(buffer);
				}
				outputStream.flush();
				return FileUtils.RESULT_SUCCESS;
			}
		}
		return FileUtils.RESULT_FAIL;
	}
}
